/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/9/26 10:56
 */
package com.gitee.mechanic.core.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

import java.io.File;
import java.io.IOException;

/**
 * Spring Resource 工具类
 *
 * @author mechanic
 */
public class ResourceUtils {

    /**
     * 获取资源目录的绝对路径
     *
     * @param resourceDir 资源目录
     * @return 绝对路径
     * @throws IOException 资源文件不存在时抛出的异常
     */
    public static String getAbsolutePath(String resourceDir) throws IOException {

        Assert.notNull(resourceDir, "资源目录不能为空");

        Resource resource = new ClassPathResource(resourceDir);
        if (resource.exists()) {
            File file = resource.getFile();
            if (file.isDirectory()) {
                return resource.getFile().getAbsolutePath() + "/";
            } else {
                return resource.getFile().getAbsolutePath();
            }
        } else {
            throw new IOException(resourceDir + " 不存在");
        }
    }

    /**
     * 获取资源目录的绝对路径
     *
     * @param filename 文件路径
     * @return 绝对路径
     */
    public static String getPath(String filename) {
        Assert.notNull(filename, "文件路径不能为空");
        ClassPathResource resource = new ClassPathResource(filename);
        return resource.getPath();
    }

    /**
     * 将路径格式化成 URL.getResourc() 需要的格式
     *
     * @param path 路径
     * @return 格式化后的路径
     */
    private static String formatPath(String path) {
        Assert.notNull(path, "资源目录不能为空");

        path = path.replaceAll("\\\\", "/");
        while (path.contains("//")) {
            path = path.replaceAll("//", "/");
        }

        path = (path.startsWith("/") || path.startsWith("\\")) ? path.substring(1) : path;
        path = !path.endsWith("/") ? (path + "/") : path;
        return path;
    }
}
